package domain;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.util.LinkedList;

import serializables.AddSongCommand;
import serializables.Command;
import serializables.Song;

public class ReceiveCommandThread extends Thread {
	
	private static final int COMMAND_PORT = 1236;
	private static final int REQUEST_UPDATE = 0;
	private static DatagramSocket dgramSocket;
	private static DatagramPacket inPacket, outPacket;
	private static byte[] buffer;
	private static byte[] commandIntBuffer;

	public ReceiveCommandThread() {
		super();
		try {
			dgramSocket = new DatagramSocket(COMMAND_PORT);
		} catch (SocketException e) {
			System.out.println("socket ex: "+ e.getMessage());
		}
	}

	@Override
	public void run() {
		super.run();
		while(true){
			try{
				commandIntBuffer = new byte[1024];
				inPacket = new DatagramPacket(commandIntBuffer, commandIntBuffer.length);
				dgramSocket.receive(inPacket);
				System.out.println("received command packet");
				
				InetAddress clientAddress = inPacket.getAddress();
				int clientPort = inPacket.getPort();
				
				ByteArrayInputStream bais = new ByteArrayInputStream(commandIntBuffer);
				ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(bais));
				try {
					AddSongCommand addSongCommand = (AddSongCommand)ois.readObject();
					System.out.println("received song: " + addSongCommand.getSong().getTitle());
					Server.addSong(addSongCommand.getSong());
				
				} catch (ClassNotFoundException e) {
					System.out.println("receive command packet, class not found exception " + e);
					e.printStackTrace();
				}
				
				//executeCommand(commandInt, clientAddress, clientPort);
			}catch (IOException e) {
				System.out.println("receive command packet, io exception " + e);
			}
		}
	}

	private void executeCommand(int commandInt, InetAddress clientAddress,
			int clientPort) {
		if(commandInt == REQUEST_UPDATE){
			
			try {
				ByteArrayOutputStream baos = new ByteArrayOutputStream(256);
				ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(baos));
				
				oos.flush();
				oos.writeObject(Server.getServerStatus());
				oos.flush();
				
				//retrieves byte array
				byte[] sendBuffer = baos.toByteArray();
				outPacket = new DatagramPacket(sendBuffer, sendBuffer.length, clientAddress, clientPort);
				dgramSocket.send(outPacket);
				oos.close();
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}
	
	

}
